package cn.dankal.flyaudio.store;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;

import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.openapi.IWXAPI;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import byc.imagewatcher.ImageWatcher;
import byc.imagewatcher.ImageWatcherHelper;
import cn.dankal.basiclib.DankalApplication;
import cn.dankal.basiclib.base.activity.BaseActivity;
import cn.dankal.basiclib.pojo.CommentsEntity;
import cn.dankal.basiclib.pojo.ProductEntity;
import cn.dankal.basiclib.pojo.req.ShoppingCarItemReq;
import cn.dankal.basiclib.util.ActivityUtils;
import cn.dankal.basiclib.util.AppUtils;
import cn.dankal.basiclib.util.DisplayHelper;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.basiclib.util.Util;
import cn.dankal.basiclib.util.WebViewUtil;
import cn.dankal.basiclib.util.image.PicUtils;
import cn.dankal.basiclib.widget.DKWebView;
import cn.dankal.basiclib.widget.banner.DkBanner;
import cn.dankal.basiclib.widget.banner.IViewHolder;
import cn.dankal.basiclib.widget.banner.OnBannerItemClickListener;
import cn.dankal.basiclib.widget.banner.VH;
import cn.dankal.flyaudio.R;
import cn.dankal.flyaudio.adapter.EvaluateImgAdapter;
import cn.dankal.flyaudio.contract.ProductDetailContract;
import cn.dankal.flyaudio.current.post.BannerItemView;
import cn.dankal.flyaudio.dialog.ShareDialog;
import cn.dankal.flyaudio.entity.ShoppingOrderEntity;
import cn.dankal.flyaudio.friend.ChatShareActivity;
import cn.dankal.flyaudio.friend.pickimage.ImageUtil;
import cn.dankal.flyaudio.friend.utils.ShareUtils;
import cn.dankal.flyaudio.pop.AddShopCarPop;
import cn.dankal.flyaudio.presenter.ProductDetailPresenter;
import cn.dankal.flyaudio.presenter.UserServiceActivity;
import cn.dankal.flyaudio.view.StarView;

public class ProductDetailActivity extends BaseActivity implements View.OnClickListener, ProductDetailContract.View {

    private ProductDetailPresenter productDetailPresenter;

    private DkBanner dkBanner;

    private TextView productName;

    private TextView productPrice;

    private TextView productSales;

    private TextView addShopCarView;
    private AddShopCarPop shopCarPop;
    private AddShopCarPop addShopCarPop1;
    private AddShopCarPop addShopCarPop2;

    private TextView buyView;

    private CommentsEntity commentsEntity;

    private View favoritesLayoutView;

    private TextView favoritesView;

    private View shopCarView;

    private View serviceView;

    private String productId;

    private ProductEntity entity;

    private ImageView itemIvAvatar, ivLike, ivEmail;
    private TextView itemTvName, itemTvTime, itemTvContent, tvEvaluate;
    private StarView ratingBar;
    private RecyclerView itemRvImg;
    private DKWebView webView;
    private ImageWatcherHelper iwHelper;//方式二

    private String skuItemUuid;
    private String skuItemDesc;
    private int skuItemNum;
    private TextView skuView;
    private EvaluateImgAdapter evaluateImgAdapter;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_product_detail;
    }

    @Override
    protected void initComponents() {

        // 如果不是透明状态栏，你需要给ImageWatcher标记 一个偏移值，以修正点击ImageView查看的启动动画的Y轴起点的不正确
        iwHelper = ImageWatcherHelper.with(this, new GlideSimpleLoader()) // 一般来讲， ImageWatcher 需要占据全屏的位置
                .setErrorImageRes(R.mipmap.error_picture) // 配置error图标 如果不介意使用lib自带的图标，并不一定要调用这个API
                .setOnStateChangedListener(new ImageWatcher.OnStateChangedListener() {
                    @Override
                    public void onStateChangeUpdate(ImageWatcher imageWatcher, ImageView clicked, int position, Uri uri, float animatedValue, int actionTag) {
                        Log.e("IW", "onStateChangeUpdate [" + position + "][" + uri + "][" + animatedValue + "][" + actionTag + "]");
                    }

                    @Override
                    public void onStateChanged(ImageWatcher imageWatcher, int position, Uri uri, int actionTag) {
                        if (actionTag == ImageWatcher.STATE_ENTER_DISPLAYING) {
//                            Toast.makeText(getApplicationContext(), "点击了图片 [" + position + "]" + uri + "", Toast.LENGTH_SHORT).show();
                        } else if (actionTag == ImageWatcher.STATE_EXIT_HIDING) {
//                            Toast.makeText(getApplicationContext(), "退出了查看大图", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
        productId = getIntent().getStringExtra("uuid");
        productDetailPresenter = new ProductDetailPresenter();
        productDetailPresenter.attachView(this);
        findViewById(R.id.iv_share).setOnClickListener(this);
        dkBanner = findViewById(R.id.dk_banner);
        skuView = findViewById(R.id.tv_sku);
        webView = findViewById(R.id.dk_webview);
        productName = findViewById(R.id.tv_product_name);
        productPrice = findViewById(R.id.tv_price);
        productSales = findViewById(R.id.tv_sales);
        ivLike = findViewById(R.id.iv_like);
        ivEmail = findViewById(R.id.iv_email);

        addShopCarView = findViewById(R.id.tv_shop_car);
        buyView = findViewById(R.id.tv_shop_buy);
        favoritesLayoutView = findViewById(R.id.ll_shop_favorites);
        favoritesView = findViewById(R.id.tv_shop_favorites);
        shopCarView = findViewById(R.id.ll_shop_car);
        serviceView = findViewById(R.id.ll_shop_service);

        itemIvAvatar = findViewById(R.id.item_iv_avatar);
        itemTvName = findViewById(R.id.item_tv_name);
        ratingBar = findViewById(R.id.ratingBar);
        itemTvTime = findViewById(R.id.item_tv_time);
        itemTvContent = findViewById(R.id.item_tv_content);
        itemRvImg = findViewById(R.id.item_rv_img);

        itemRvImg.setLayoutManager(new GridLayoutManager(this, 3, GridLayoutManager.VERTICAL,
                false));
        evaluateImgAdapter = new EvaluateImgAdapter();
        itemRvImg.setAdapter(evaluateImgAdapter);
        tvEvaluate = findViewById(R.id.tv_evaluate);
        shopCarView.setOnClickListener(this);
        findViewById(R.id.rl_user_service).setOnClickListener(this);
        findViewById(R.id.iv_onback).setOnClickListener(this);
        findViewById(R.id.rl_sku_layout).setOnClickListener(this);
        productDetailPresenter.fetchProductDetail(productId);
        productDetailPresenter.getEvaluate(productId, 1);
        serviceView.setOnClickListener(this);
        tvEvaluate.setOnClickListener(this);
        favoritesLayoutView.setOnClickListener(this);
        shopCarView.setOnClickListener(this);
        buyView.setOnClickListener(this);
        addShopCarView.setOnClickListener(this);
        ivLike.setOnClickListener(this);
        ivEmail.setOnClickListener(this);
    }

    //记得重写返回键哦
    @Override
    public void onBackPressed() {
//        //方式一
//        if (!vImageWatcher.handleBackPressed()) {
//            super.onBackPressed();
//        }
        //方式二
        if (!iwHelper.handleBackPressed()) {
            super.onBackPressed();
        }
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_share) {
            new ShareDialog(this).setOnShareListener(new ShareDialog.OnShareListener() {
                @Override
                public void wechatShare() {
                    ivWeChat(1, convertViewToBitmap(findViewById(R.id.cl_content)));
                }

                @Override
                public void wechatCircleShare() {
                    ivWeChat(2, convertViewToBitmap(findViewById(R.id.cl_content)));
                }

                @Override
                public void appShare() {
                    ShareUtils.getInstance().setShareBitmap(convertViewToBitmap(findViewById(R.id.cl_content)));
                    ActivityUtils.startActivity(ChatShareActivity.class);
                }
            }).showPopupWindow(findViewById(android.R.id.content));

        } else if (R.id.iv_onback == id) {
            onBackPressed();
        } else if (R.id.ll_shop_service == id) {
            //客服
            Intent intent = new Intent(ActivityUtils.getTopActivity(), WebViewActivity.class);
            intent.putExtra("url", "https://ykefu.suanyun.shop/index/index?code=vOWRbfuH3SWF0yYFJIXazW00LzJy4Ffuh%2B2%2BPwu7UwMYbKkkv46UYY5mAizTXAnxkHkL0jlSfTt7Fk7KhIOVyxxfGkEYZzQn3YyffATwokPMI%2FYx");
            startActivity(intent);
        } else if (R.id.ll_shop_car == id) {
            //进入购物车
            ActivityUtils.startActivity(ShoppingCarActivity.class);
        } else if (R.id.ll_shop_favorites == id) {
            //点击收藏
            if (favoritesLayoutView.isSelected()) {
                productDetailPresenter.cancelFavoritesProduct(productId);
            } else {
                productDetailPresenter.favoritesProduct(productId);
            }
        } else if (R.id.tv_shop_car == id) {
            //加入购物车
            if (entity == null) return;

            if (entity.getItems() == null || entity.getItems().isEmpty()) {
                productDetailPresenter.addShopCar("-1", 1);
                return;
            }
            if (entity.getItems().size() == 1) {
                productDetailPresenter.addShopCar(entity.getItems().get(0).getUuid(), 1);
                return;
            }
            if (TextUtils.isEmpty(skuItemUuid)) {
                if (shopCarPop == null) {
                    shopCarPop =
                            new AddShopCarPop(this).setAddShopListener(new AddShopCarPop.AddShopCarListener() {
                                @Override
                                public void doAdd(int num, String itemUuid, String desc) {
                                    if (TextUtils.isEmpty(itemUuid)) {
                                        ToastUtils.showShort("没有库存!");
                                        return;
                                    }
                                    productDetailPresenter.addShopCar(itemUuid, num);
                                }

                                @Override
                                public void doBuy(int num, String itemUuid, String itemDesc) {

                                }
                            });
                }
                if (!shopCarPop.isShowing()) {
                    shopCarPop.setShop(entity);
                    shopCarPop.showPopupWindow(findViewById(android.R.id.content));
                }
            } else {
                productDetailPresenter.addShopCar(skuItemUuid, skuItemNum);
            }
//            productDetailPresenter.addShopCar(productId, 1);
        } else if (R.id.tv_evaluate == id) {
            Bundle bundle = new Bundle();
            bundle.putString("id", productId);
            ActivityUtils.startActivity(bundle, CommentsListActivity.class);
        } else if (R.id.rl_user_service == id) {
            Bundle bundle = new Bundle();
            bundle.putString("webContent", entity.getCustomerService());
            ActivityUtils.startActivity(bundle, UserServiceActivity.class);
        } else if (R.id.rl_sku_layout == id) {
            if (addShopCarPop2 == null) {
                addShopCarPop2 =
                        new AddShopCarPop(this).setAddShopListener(new AddShopCarPop.AddShopCarListener() {
                            @Override
                            public void doAdd(int num, String itemUuid, String desc) {
                                if (TextUtils.isEmpty(itemUuid)) {
                                    ToastUtils.showShort("没有库存!");
                                    return;
                                }
                                productDetailPresenter.addShopCar(itemUuid, num);
                            }

                            @Override
                            public void doBuy(int num, String itemUuid, String itemDesc) {

                            }
                        });
            }
            if (!addShopCarPop2.isShowing()) {
                addShopCarPop2.setShop(entity);
                addShopCarPop2.showPopupWindow(findViewById(android.R.id.content));
            }
        } else if (R.id.iv_like == id) {
            if (commentsEntity != null) {
                if ("true".equals(commentsEntity.getiLike())) {
                    productDetailPresenter.unLike(commentsEntity.getUuid());
                } else {
                    productDetailPresenter.like(commentsEntity.getUuid());
                }
            }
        } else if (R.id.iv_email == id) {
            if (commentsEntity != null) {
                Bundle bundle = new Bundle();
                bundle.putString("uuid", commentsEntity.getUuid());
                ActivityUtils.startActivity(bundle, EvaluateListActivity.class);
            }
        } else if (R.id.tv_shop_buy == id) {
            if (entity == null) return;
            if (entity.getItems() == null || entity.getItems().isEmpty()) {
                //规格为空，直接购买，规格为null
                List<ShoppingCarItemReq> req = new ArrayList<>();
                ShoppingCarItemReq shoppingCarItemReq = new ShoppingCarItemReq();
                shoppingCarItemReq.setItemUuid("");
                shoppingCarItemReq.setItemCount("1");
                req.add(shoppingCarItemReq);
                ShoppingOrderEntity shoppingOrderEntity = new ShoppingOrderEntity();
//                    shoppingOrderEntity.setProducts(shopCarEntities);
                shoppingOrderEntity.setItemReq(req);
                Intent intent = new Intent(ProductDetailActivity.this, ConfirmOrderActivity.class);
                intent.putExtra("products", shoppingOrderEntity);
                startActivity(intent);
                return;
            }
            if (entity.getItems().size() == 1) {
                //规格为1，直接购买，传唯一的规格uuid
                List<ShoppingCarItemReq> req = new ArrayList<>();
                ShoppingCarItemReq shoppingCarItemReq = new ShoppingCarItemReq();
                shoppingCarItemReq.setItemUuid(entity.getItems().get(0).getUuid());
                shoppingCarItemReq.setItemCount("1");
                req.add(shoppingCarItemReq);
                ShoppingOrderEntity shoppingOrderEntity = new ShoppingOrderEntity();
//                    shoppingOrderEntity.setProducts(shopCarEntities);
                shoppingOrderEntity.setItemReq(req);
                Intent intent = new Intent(ProductDetailActivity.this, ConfirmOrderActivity.class);
                intent.putExtra("products", shoppingOrderEntity);
                startActivity(intent);
                return;
            }
            if (addShopCarPop1 == null) {
                addShopCarPop1 =
                        new AddShopCarPop(this).setShop(entity).isBuy().setAddShopListener(new AddShopCarPop.AddShopCarListener() {
                            @Override
                            public void doAdd(int num, String itemUuid, String desc) {
                                if (TextUtils.isEmpty(itemUuid)) {
                                    ToastUtils.showShort("没有库存!");
                                    return;
                                }
                                productDetailPresenter.addShopCar(itemUuid, num);
                            }

                            @Override
                            public void doBuy(int num, String itemUuid, String itemDesc) {
                                if (TextUtils.isEmpty(itemUuid)) {
                                    ToastUtils.showShort("没有库存!");
                                    return;
                                }
                                List<ShoppingCarItemReq> req = new ArrayList<>();
                                ShoppingCarItemReq shoppingCarItemReq = new ShoppingCarItemReq();
                                shoppingCarItemReq.setItemUuid(itemUuid);
                                shoppingCarItemReq.setItemCount(num + "");
                                req.add(shoppingCarItemReq);
                                ShoppingOrderEntity shoppingOrderEntity = new ShoppingOrderEntity();
//                    shoppingOrderEntity.setProducts(shopCarEntities);
                                shoppingOrderEntity.setItemReq(req);
                                Intent intent = new Intent(ProductDetailActivity.this, ConfirmOrderActivity.class);
                                intent.putExtra("products", shoppingOrderEntity);
                                startActivity(intent);
                            }
                        });
            }
            if (!addShopCarPop1.isShowing()) {
                addShopCarPop1.setShop(entity);
                addShopCarPop1.showPopupWindow(findViewById(android.R.id.content));
            }
        }
    }

    public Bitmap convertViewToBitmap(View view) {

        Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),

                Bitmap.Config.ARGB_8888);

//利用bitmap生成画布

        Canvas canvas = new Canvas(bitmap);

//把view中的内容绘制在画布上

        view.draw(canvas);


        return compressBitmap(bitmap);

    }
    public static final int IMAGE_SIZE=32768;//微信分享图片大小限制

    private Bitmap compressBitmap(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int quality = 100;
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
        Log.d("ProcutDetailActivity","压缩前:"+baos.toByteArray().length);
        // 循环判断压缩后图片是否超过限制大小
        while(baos.toByteArray().length > IMAGE_SIZE && quality != 10)  {
            baos.reset();
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
            quality -= 10;
        }
        if(baos.toByteArray().length>IMAGE_SIZE){
            //如果还大，启用最低压缩
            baos.reset();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 1, baos);
        }
        Bitmap newBitmap = BitmapFactory.decodeStream(new ByteArrayInputStream(baos.toByteArray()), null, null);
        Log.d("ProcutDetailActivity","压缩后:"+baos.toByteArray().length);
        return newBitmap;
    }
    @Override
    protected void onDestroy() {
        productDetailPresenter.detachView();
        super.onDestroy();
    }

    @Override
    public void handleProductDetailResult(ProductEntity entity) {
        productUrl = entity.getMainImg();
        initBanner(entity.getImgList());
        this.entity = entity;
        WebSettings settings = webView.getSettings();
//        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        //支持javascript
        settings.setJavaScriptEnabled(true);
// 设置可以支持缩放
        settings.setSupportZoom(true);
// 设置出现缩放工具
        settings.setBuiltInZoomControls(true);
//扩大比例的缩放
        settings.setUseWideViewPort(true);
//自适应屏幕
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setLoadWithOverviewMode(true);
        settings.setTextSize(WebSettings.TextSize.LARGEST);
//        settings.setLoadWithOverviewMode(true);
        WebViewUtil.loadData(webView, entity.getDetail());
        webView.setWebViewClient(new WebViewUtil.MyWebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                String javascript = "javascript:function ResizeImages() {" +
                        "var myimg,oldwidth;" +
                        "var maxwidth = document.body.clientWidth;" +
                        "for(i=0;i <document.images.length;i++){" +
                        "myimg = document.images[i];" +
                        "if(myimg.width > maxwidth){" +
                        "oldwidth = myimg.width;" +
                        "myimg.width = maxwidth;" +
                        "}" +
                        "}" +
                        "}";
                view.loadUrl(javascript);
                view.loadUrl("javascript:ResizeImages();");
            }
        });
        productName.setText(entity.getProductName());
        productPrice.setText(entity.getShowPrice());
        productSales.setText(entity.getSaleCount() + "\n销量");
        favoritesLayoutView.setSelected(entity.getFavorite());
        if (entity.getFavorite()) {
            favoritesView.setText("取消收藏");
        } else {
            favoritesView.setText("收藏");
        }

    }

    @Override
    public void favoritesProductSuccess() {
        favoritesLayoutView.setSelected(true);
        favoritesView.setText("取消收藏");
    }

    @Override
    public void cancelFavoritesProductSuccess() {
        favoritesLayoutView.setSelected(false);
        favoritesView.setText("收藏");
    }

    @Override
    public void addSuccess() {

    }


    @Override
    public void evaluateSuccess(List<CommentsEntity> list) {
        if (list.size() > 0) {
            tvEvaluate.setText("评价（" + list.size() + "）");
            commentsEntity = list.get(0);
            setCommentText();
        } else {
            tvEvaluate.setText("评价(0)");
            findViewById(R.id.include_evaluate).setVisibility(View.GONE);
        }
    }

    private void setCommentText() {
        String avatar = "";
        String name = "";
        if (commentsEntity.getAppUser() != null) {
            avatar = commentsEntity.getAppUser().getAvatar();
            name = commentsEntity.getAppUser().getUsername();
        }
        PicUtils.loadAvatar(avatar, itemIvAvatar);
        itemTvContent.setText(commentsEntity.getContent());
        itemTvName.setText(name);
        itemTvTime.setText(commentsEntity.getCreatedDatetime());
        if ("true".equals(commentsEntity.getiLike())) {
            ivLike.setImageResource(R.mipmap.ic_awesome);
        } else {
            ivLike.setImageResource(R.mipmap.ic_awesome_un);
        }

        if (commentsEntity.getImgList() != null) {
            evaluateImgAdapter.addDatas(commentsEntity.getImgList(), true);
        }

        switch (commentsEntity.getScoreType()) {
            case "POOR":
                ratingBar.setMark(1f);
                break;
            case "AVERAGE":
                ratingBar.setMark(2f);
                break;
            case "GOOD":
                ratingBar.setMark(3f);
                break;
        }
    }

    @Override
    public void likeSuccess() {
        commentsEntity.setiLike("true");
        setCommentText();
    }

    @Override
    public void unLikeSuccess() {
        commentsEntity.setiLike("false");
        setCommentText();
    }

    private String productUrl = "";

    private void initBanner(List<String> bannerDate) {
        dkBanner.setIndicatorPoint(R.drawable.oval_indicator, R.drawable.oval_indicator_unselect,
                DisplayHelper.dp2px(AppUtils.getApp(), 10), DisplayHelper.dp2px(AppUtils.getApp(), 10));
        dkBanner.setOnItemClickListener(new OnBannerItemClickListener() {
            @Override
            public void onItemClick(View view, Object o, int postion, int realPostion) {
                List<Uri> uris = new ArrayList<>();
                Uri uri = Uri.parse(o.toString());
                uris.add(uri);
                iwHelper.show(uris, 0);
            }
        });
        dkBanner.setVpAdapter(bannerDate, new IViewHolder<String>() {
            @Override
            public VH<String> create() {
                return new BannerItemView();
            }
        });

    }

    private IWXAPI api;

    //分享到朋友圈或者朋友圈
    private void ivWeChat(int type, Bitmap bitmap) {
        api = DankalApplication.instance().getIWXAPI();
        WXImageObject imgObj = new WXImageObject(bitmap);
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;

//设置缩略图
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bitmap, 200, 200, true);
        bitmap.recycle();
        msg.thumbData = Util.bmpToByteArray(thumbBmp, true);

//构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        if (type == 1) {
            req.scene = SendMessageToWX.Req.WXSceneSession;
        } else {
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
        }
//调用api接口，发送数据到微信
        api.sendReq(req);
    }

}
